import type { RequestConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { message } from 'antd';
// import { LOGIN_PATH } from './utils/constants';
const LOGIN_PATH = '/login';

// 错误处理方案： 错误类型
enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 3,
  REDIRECT = 9,
}

// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  errorCode?: number;
  errorMessage?: string;
  showType?: ErrorShowType;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */

export const errorConfig: RequestConfig = {
  // 请求拦截器
  requestInterceptors: [
    (url, options) => {
      console.log('请求拦截器', url, options);
      return {
        url,
        options: {
          ...options,
          headers: {
            ...options.headers,
            'X-SHOP-ID': localStorage.getItem('shopId') ?? 0,
          },
          data: options.data?.current
            ? { ...options.data, pageNo: options?.data?.current }
            : options.data,
          timeout: 90 * 1000,
          params: options.params?.current
            ? { ...options.params, pageNo: options?.params?.current }
            : options.params,
        },
      };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    [
      // @ts-ignore
      (response) => {
        const { data } = response as unknown as ResponseStructure;
        if (data.code && data.code !== 0) {
          if (data.code === 401) {
            history.push(LOGIN_PATH);
            localStorage.clear();
            message.error('登录已过期');
            setTimeout(() => {
              window.location.reload();
            }, 1000);
          } else {
            message.error(data.message);
          }
          return Promise.reject(data.message);
        }
        // console.log(response);
        return response;
      },
      (error: any) => {
        return Promise.reject(error);
      },
    ],
  ],
};
